package face.jvm;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by zhangyanfei on 2019/6/25.
 * 同步队列
 * @author zhangyanfei
 * @date 2019/06/25
 */
public class ReadAndWriteLockDemo {

    static class MyCache {
        private volatile Map<String, Object> map = new HashMap<>();

        private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

        public void put(String key, Object value) {
            reentrantReadWriteLock.writeLock().lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t 正在写入：" + key);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                map.put(key, value);
                System.out.println(Thread.currentThread().getName() + "\t 写入完成：" + key);
            } finally {
                reentrantReadWriteLock.writeLock().unlock();
            }

        }

        public void get(String key) {
            System.out.println(Thread.currentThread().getName() + "\t 正在读：" + key);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "\t 读完毕：" + key);
        }

        public void del() {

        }
    }

    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.put(finalI + "", finalI + "");
            }, String.valueOf(i)).start();
        }

    }
}
